<?php

namespace App\Models\OpenShop\Common;

use App\Models\BaseModel;
use App\Models\Common\ResourcesModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\Kms\Home\HomeService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class SiteLocationMallModel extends BaseModel
{
    protected $table = 'site_location_mall';

    protected $fillable = [
        'mallId',
        'mallName',
        'branch',
        'largeClassify',
        'smallClassify',
        'label',
        'topList',
        'price',
        'facilitiesRating',
        'environmentRating',
        'serviceRating',
        'star',
        'phone',
        'commentNum',
        'businessStatus',
        'province',
        'city',
        'district',
        'area',
        'address',
        'lng',
        'lat',
        'car',
        'healthcare',
        'food',
        'study',
        'scenicSpot',
        'Shopping',
        'marry',
        'beauty',
        'homeFurnishing',
        'cinema',
        'homestay',
        'parentChild',
        'recreation',
        'hotel',
        'KSong',
        'pat',
        'life',
        'sport',
        'traffic',
        'foodRatio',
        'shopTotalCount',
        'grade',
        'wgNumber',
        'status',
        'recommendFloor',
        'floorSymbioticBrand',
        'provinceCode',
        'cityCode',
        'districtCode',
    ];

    protected $appends = [
        'nameText'
    ];

    const SITE_MALL_GRADE_S = 6;
    const SITE_MALL_GRADE_A = 5;
    const SITE_MALL_GRADE_B = 4;
    const SITE_MALL_GRADE_C = 3;

    const SITE_MALL_GRADE_MAPPING = [
        self::SITE_MALL_GRADE_S => 'S级',
        self::SITE_MALL_GRADE_A => 'A级',
        self::SITE_MALL_GRADE_B => 'B级',
        self::SITE_MALL_GRADE_C => 'C级',
    ];

    const MALL_BUSINESS_STATUS_OK    = 1;
    const MALL_BUSINESS_STATUS_NO    = 0;
    const MALL_BUSINESS_STATUS_CLOSE = 2;

    const MALL_BUSINESS_STATUS_MAPPING = [
        self::MALL_BUSINESS_STATUS_NO    => '未开业',
        self::MALL_BUSINESS_STATUS_OK    => '已开业',
        self::MALL_BUSINESS_STATUS_CLOSE => '已关闭',
    ];


    public function logRel(): HasMany
    {
        return $this->hasMany(OpenShopSiteLocationExamineLogModel::class, 'orderNo', 'wgNumber');
    }

    public function resourceWithMapRel()
    {
        return $this->hasOne(ResourcesModel::class, 'name', 'wgNumber')
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT);
    }


    /**
     * 定义一个访问器
     * @return mixed
     */
    public function getNameTextAttribute()
    {
        return $this->mallName;
    }


    /**
     * 根据商场ID获得推荐楼层以及共生品牌
     * @param string $mallId
     * @return array
     */
    public static function getRecommendFloorInfo(string $mallId): array
    {
        $model = self::query()
                     ->where('mallId', $mallId)
                     ->select(['recommendFloor', 'floorSymbioticBrand'])
                     ->first();
        if (null === $model) {
            return [
                'recommendFloor'      => '',
                'floorSymbioticBrand' => [],
            ];
        } else {
            return [
                'recommendFloor'      => $model->recommendFloor,
                'floorSymbioticBrand' => $model->floorSymbioticBrand,
                //'floorSymbioticBrand' => explode(',', $model->floorSymbioticBrand),
            ];
        }
    }


    /**
     * 关联大客户部选址任务
     * @return HasOne
     */
    public function siteTaskRel(): HasOne
    {
        return $this->hasOne(CustomerDepartmentTaskModel::class, 'wgNumber', 'wgNumber');
    }

    /**
     * 首页查询条件构造
     *
     * @param int $regionSelectionType
     * @param string $region
     * @param string $regionValue
     * @return Builder|mixed
     */
    public static function buildHomeSearchQuery(int $regionSelectionType, string $region, string $regionValue)
    {
        $query = function ($query) use ($region) {
            return $query->where("id", 0);
        };
        switch ($regionSelectionType) {
            case HomeService::REGION_SELECTION_TYPE_1:
                $region = attributeGet(
                    OpenShopOrganizationManageModel::allOrganizationManage()
                                                   ->where("type", "<>",
                                                       OpenShopOrganizationManageModel::HEADQUARTERS_ID)
                                                   ->where("name", $region)
                                                   ->first(),
                    "regionRel",
                    collect([])
                );

                $provinceCodeGroup = $region->pluck("provinceCode")->values()->toArray();
                if ($provinceCodeGroup) {
                    $query = function ($query) use ($provinceCodeGroup) {
                        return $query->whereIn("provinceCode", $provinceCodeGroup);
                    };
                }
                break;
            case HomeService::REGION_SELECTION_TYPE_2:
                $query = function ($query) use ($regionValue) {
                    return $query->where("provinceCode", $regionValue);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_3:
                $query = function ($query) use ($regionValue) {
                    return $query->where("cityCode", $regionValue);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_0:
                $query = null;
                break;
        }
        return self::query()->when($query, function ($subQuery) use ($query) {
            return $subQuery->where($query);
        });
    }
}
